package cfca.seal.web.tag;

import cfca.seal.bean.AdminUser;
import cfca.seal.bean.Organization;
import cfca.seal.dao.main.IOrganizationDao;
import cfca.seal.web.system.SessionManager;
import cfca.seal.web.tag.base.TemplateDirectiveModelBase;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;

@Component
public class OrganizationSelectTag extends TemplateDirectiveModelBase
{

  @Resource
  IOrganizationDao dao;

  public String process(Environment env, Map paramsMap, TemplateModel[] loopVars, TemplateDirectiveBody body)
    throws TemplateException, IOException
  {
    AdminUser manager = SessionManager.getManager(this.request);
    StringBuffer sf = new StringBuffer();
    sf.append("<select size=\"1\" class=\"").append(this.className).append("\" id=\"").append(this.elementId).append("\" name = \"").append(this.elementName).append("\" >");
    try
    {
      if (manager.getUserType() > 0) {
        Organization organization = this.dao.getOrganizationById(manager.getOrganizationId());
        sf.append("");
        sf.append("<option value=\"").append(organization.getId()).append("\" ");
        sf.append("selected = \"selected\"");
        sf.append(" >").append(organization.getName()).append("</option>");
      } else {
        List list = this.dao.getAll();
        sf.append("<option value=\"\">--请选择--</option>");

        if ((list != null) && (list.size() > 0)) {
          for (int i = 0; i < list.size(); i++) {
            Organization org = (Organization)list.get(i);
            sf.append("<option value=\"").append(org.getId()).append("\" ");

            if (org.getId().equals(this.elementValue)) {
              sf.append("selected = \"selected\"");
            }

            sf.append(" >").append(org.getName()).append("</option>");
          }
        }
      }
      sf.append("</select>");
    } catch (Exception e) {
      e.printStackTrace();
    }

    return sf.toString();
  }
}